<template>
	<view class="container">
		<view class="repair-form">
			<uni-forms ref="form" :value="formData" :rules="rules">

				<uni-forms-item label="联系人" required name="contactName">
					<uni-easyinput v-model="formData.contactName" placeholder="请输入联系人姓名" />
				</uni-forms-item>

				<uni-forms-item label="联系电话" required name="contactPhone">
					<uni-easyinput v-model="formData.contactPhone" placeholder="请输入联系电话" />
				</uni-forms-item>

				<uni-forms-item label="报修地点" required name="location">
					<uni-easyinput v-model="formData.location" placeholder="请输入具体位置" />
				</uni-forms-item>


				<uni-forms-item label="报修内容" required name="content">
					<uni-easyinput v-model="formData.content" type="textarea" placeholder="请详细描述问题（不超过500字）"
						maxlength="500" />
				</uni-forms-item>

				<uni-forms-item label="图片上传" name="images" required>
					<view class="image-uploader">
						<view class="image-item" v-for="(item, index) in imageList" :key="index">
							<image :src="item.path" mode="aspectFill" @click="previewImage(index)"></image>
							<text class="delete-icon" @click.stop="deleteImage(index)">×</text>
						</view>

						<view class="image-item add-image" @click="chooseImage" v-if="imageList.length < maxImageCount">
							<text class="add-icon">+</text>
							<text class="add-text">添加图片</text>
						</view>
					</view>
					<text class="tips">请上传至少一张故障图片，最多上传8张，每张不超过10M</text>
				</uni-forms-item>
			</uni-forms>

			<button class="submit-btn" type="primary" @click="submitForm">提交报修</button>
		</view>
	</view>
</template>

<script>
	import {
		http
	} from '@/utils/request.js';
	import {
		getToken
	} from '@/utils/auth.js';

	export default {
		data() {
			return {
				formData: {
					type: 1,
					contactName: '',
					contactPhone: '',
					location: '',
					content: '',
				},
				typeIndex: 0,
				typeOptions: [{
					value: 1,
					text: '水电维修'
				}, {
					value: 2,
					text: '家具维修'
				}, {
					value: 3,
					text: '空调维修'
				}, {
					value: 4,
					text: '其他设施'
				}],
				imageList: [],
				maxImageCount: 8,
				rules: {
					contactName: {
						rules: [{
							required: true,
							errorMessage: '请输入联系人姓名'
						}]
					},
					contactPhone: {
						rules: [{
							required: true,
							errorMessage: '请输入联系电话'
						}, {
							pattern: /^1[3-9]\d{9}$/,
							errorMessage: '请输入正确的手机号码'
						}]
					},
					location: {
						rules: [{
							required: true,
							errorMessage: '请输入报修地点'
						}]
					},
					type: {
						rules: [{
							required: true,
							errorMessage: '请选择报修类型'
						}]
					},
					content: {
						rules: [{
							required: true,
							errorMessage: '请输入报修详情'
						}]
					}
				},
			}
		},
		methods: {
			// 选择类型
			bindTypeChange(e) {
				this.typeIndex = e.detail.value;
				this.formData.type = this.typeOptions[this.typeIndex].value;
			},

			// 选择图片
			chooseImage() {
				uni.chooseImage({
					count: this.maxImageCount - this.imageList.length,
					sizeType: ['compressed'], // 压缩图
					sourceType: ['album', 'camera'], // 相册或相机
					success: (res) => {
						// 添加新选择的图片
						const tempFilePaths = res.tempFilePaths.map(path => {
							return {
								path: path
							}
						});
						this.imageList = [...this.imageList, ...tempFilePaths];
					}
				});
			},

			// 预览图片
			previewImage(index) {
				const urls = this.imageList.map(item => item.path);
				uni.previewImage({
					urls: urls,
					current: urls[index]
				});
			},

			// 删除图片
			deleteImage(index) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					success: (res) => {
						if (res.confirm) {
							this.imageList.splice(index, 1);
						}
					}
				});
			},

			// 表单提交
			submitForm() {
				// 检查是否上传了图片
				if (this.imageList.length === 0) {
					uni.showToast({
						title: '请上传至少一张故障图片',
						icon: 'none'
					});
					return;
				}

				this.$refs.form.validate().then(res => {
					// 表单验证通过
					this.uploadFormWithImages();
				}).catch(err => {
					console.log('表单错误：', err);
				});
			},

			// 上传表单和图片
			uploadFormWithImages() {
				if (this.imageList.length === 0) {
					uni.showModal({
						title: '提示',
						content: '请上传至少一张故障图片',
						showCancel: false
					});
					return;
				}

				this.doUpload();
			},

			// 执行上传
			doUpload() {
				uni.showLoading({
					title: '提交中...'
				});

				// 准备文件上传
				const filePaths = this.imageList.map(item => item.path);

				// 使用uni.uploadFile实现表单和文件一起提交
				if (filePaths.length > 0) {
					// 创建一个计数器来跟踪上传完成的图片数量
					let uploadedCount = 0;
					let uploadSuccess = true;
					let errorMsg = '';

					// 显示上传中提示
					uni.showLoading({
						title: '上传中...',
						mask: true
					});

					// 循环上传每张图片
					filePaths.forEach((path, index) => {
						uni.uploadFile({
							url: http.baseURL + '/api/repairNotice/setRepairInfo',
							filePath: path,
							name: 'files',
							formData: {
								contactName: this.formData.contactName,
								contactPhone: this.formData.contactPhone,
								location: this.formData.location,
								type: this.formData.type,
								content: this.formData.content
							},
							header: {
								'token': getToken().token
							},
							success: (res) => {
								// 增加计数器
								uploadedCount++;

								// 解析响应数据
								try {
									const result = JSON.parse(res.data);
									if (result.code !== 0) {
										uploadSuccess = false;
										errorMsg = result.msg || '提交失败';
									}
								} catch (e) {
									uploadSuccess = false;
									errorMsg = '服务器响应解析失败';
								}

								// 检查是否所有图片都已上传完成
								if (uploadedCount === filePaths.length) {
									uni.hideLoading();

									if (uploadSuccess) {
										// 全部上传成功
										uni.showToast({
											title: '提交成功',
											icon: 'success'
										});

										// 清空表单和图片
										this.resetForm();
									} else {
										// 有上传失败的情况
										uni.showToast({
											title: errorMsg || '部分图片上传失败',
											icon: 'none'
										});
									}
								}
							},
							fail: (err) => {
								uploadedCount++;
								uploadSuccess = false;
								errorMsg = '网络错误，请稍后重试';
								console.error('上传失败：', err);

								// 检查是否所有图片都已上传完成
								if (uploadedCount === filePaths.length) {
									uni.hideLoading();
									uni.showToast({
										title: errorMsg,
										icon: 'none'
									});
								}
							}
						});
					});
				} else {
					// 没有图片，直接提交表单
					http.post('/api/repairNotice/setRepairInfo', this.formData)
						.then(res => {
							uni.hideLoading();

							uni.showToast({
								title: '提交成功',
								icon: 'success'
							});

							// 清空表单和图片
							this.resetForm();
						})
						.catch(err => {
							uni.hideLoading();
							uni.showToast({
								title: err.msg || '提交失败',
								icon: 'none'
							});
						});
				}
			},

			// 重置表单
			resetForm() {
				this.formData = {
					type: 1,
					contactName: '',
					contactPhone: '',
					location: '',
					content: '',
				};
				this.typeIndex = 0;
				this.imageList = [];

				// 延迟后返回上一页或跳转到工单列表
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/order/index'
					});
				}, 1500);
			}
		}
	}
</script>

<style>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.repair-form {
		background-color: #fff;
		padding: 30rpx;
		border-radius: 20rpx;
	}

	.picker-view {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 70rpx;
		padding: 0 20rpx;
		background-color: #f8f8f8;
		border-radius: 8rpx;
	}

	.picker-text {
		font-size: 28rpx;
		color: #333;
	}

	.image-uploader {
		display: flex;
		flex-wrap: wrap;
	}

	.image-item {
		width: 200rpx;
		height: 200rpx;
		margin-right: 20rpx;
		margin-bottom: 20rpx;
		position: relative;
	}

	.image-item image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
	}

	.delete-icon {
		position: absolute;
		top: -20rpx;
		right: -20rpx;
		width: 40rpx;
		height: 40rpx;
		background-color: #f56c6c;
		color: #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		line-height: 1;
	}

	.add-image {
		border: 1px dashed #dcdfe6;
		border-radius: 8rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.add-icon {
		font-size: 60rpx;
		color: #dcdfe6;
		line-height: 1;
	}

	.add-text {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.submit-btn {
		margin-top: 40rpx;
		background-color: #2B65FE;
		color: #fff;
		border-radius: 10rpx;
	}

	.tips {
		font-size: 24rpx;
		color: #999;
		margin-top: 10rpx;
	}
</style>